package org.streets.eis.ext.rbac.pages;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.link.AbstractLink;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.streets.commons.util.GUID;
import org.streets.database.ExecMode;
import org.streets.database.SQLConnection;

import com.inmethod.grid.IGridColumn;
import com.inmethod.grid.column.CheckBoxColumn;
import org.streets.eis.entity.Position;
import org.streets.eis.setting.validatior.TableListValidator;
import org.streets.eis.pages.BasePage;
import org.streets.eis.component.dropdown.ToolBar;
import org.streets.eis.component.grid.ColumnType;
import org.streets.eis.component.grid.DateTimeColumn;
import org.streets.eis.component.grid.DefualtNavigatorLabel;
import org.streets.eis.component.grid.EditableColumn;
import org.streets.eis.component.grid.TableList;
import org.streets.eis.component.messagebox.MessageBox;
import org.streets.eis.component.messagebox.MessageBox.ReturnType;
import org.streets.eis.component.model.DataModel;
import org.streets.eis.component.model.MemoryTableModel;
import org.streets.eis.component.model.MenuItem;

public class PositionInsertPage extends BasePage {
	@Inject
	private SQLConnection conn;
	
	private TableList<Position> grid;
	
	private MemoryTableModel<Position> tableModel;
	
	private ModalWindow window;
	
	private String organId;
	
	private FeedbackPanel feedbackPanel;
	
	@SuppressWarnings("unchecked")
	public PositionInsertPage(ModalWindow window,final String organId){
		super();
		
		this.window = window;
		this.organId = organId;
				
		add(new Label("htmlTitle","增加职位"));				
		feedbackPanel = new FeedbackPanel("feedback");
		
		Form form = new Form("form"){
			private static final long serialVersionUID = 1L;
			protected void onError(){
				grid.onValidateError(feedbackPanel);
			}
		};
		add(form);
		form.add(feedbackPanel.setOutputMarkupId(true));
		
		form.add(grid = new TableList<Position>("grid", tableModel=new MemoryTableModel<Position>(),generatePositionColumns()){
			private static final long serialVersionUID = 1L;
			@Override
			protected Component newNavigationLabel(String id) {
				return new DefualtNavigatorLabel(id,this);
			}
		}.add(new TableListValidator<Position>("unique.position.name","name") {
			private static final long serialVersionUID = 1L;
			@Override
			public boolean doValidate(FormComponent<?>[] formComponents,Position object) {
				return conn.count("SELECT * FROM EIS_POSITION WHERE NAME=? AND ORGAN_ID=? AND ID<>?",new Object[]{formComponents[0].getInput(),organId,object.getId()}) == 0;
			}
			@Override
			public boolean doValidate(Map<Position, FormComponent<?>[]> editedRows) {
				List<String> tmp = new ArrayList<String>(editedRows.size());
				for (FormComponent<?>[] formComponents : editedRows.values()){
					String key = formComponents[0].getInput();
					if (tmp.contains(key)){
						return false;
					} else {
						tmp.add(key);
					}
				}
				return true;
			}
		}));
		
		grid.setAllowSelectMultiple(true);	
		grid.setClickRowToSelect(true);
		grid.setClickRowToDeselect(true);
		grid.setEditAllRowsOnInitialization(true);
		grid.setCanCancelEdit(false);
		grid.setShowNoRecordsBar(false);
		
		form.add(createToolBar());
    }

	private ToolBar createToolBar(){
		DataModel<MenuItem> model = new DataModel<MenuItem>();
		model.addChild(new DataModel<MenuItem>(new MenuItem("insert","insert","新增")));
		model.addChild(new DataModel<MenuItem>(new MenuItem("delete","delete","删除")));		
		model.addChild(new DataModel<MenuItem>(new MenuItem("post","post","保存")));
		model.addChild(new DataModel<MenuItem>(new MenuItem("close","close","关闭")));
		return new ToolBar("toolbar",model){
			private static final long serialVersionUID = 1L;
			@Override
			protected boolean needFormSubmitted(MenuItem menuItem){
				return "post".equals(menuItem.getCode());
			}
			@Override
			protected void onMenuItemClicked(AbstractLink link,DataModel<MenuItem> dataModel,AjaxRequestTarget target){
				if ("insert".equals(dataModel.getObject().getCode())){
        			insert(target);
        		}
				if ("delete".equals(dataModel.getObject().getCode())){
        			deleteSelected(target);
        		}
				if ("post".equals(dataModel.getObject().getCode())){
        			postIt(target);
        		}
				if ("close".equals(dataModel.getObject().getCode())){
					PositionInsertPage.this.window.close(target);
        		}
        	}
        };		
	}
	
	private List<IGridColumn> generatePositionColumns(){
		List<IGridColumn> columns = new ArrayList<IGridColumn>();
		columns.add(new CheckBoxColumn("check"));
		columns.add(new EditableColumn(Model.of("职位名称"), "name", "NAME") {
			private static final long serialVersionUID = 1L;
			
			@SuppressWarnings("unchecked")
			@Override
			protected void addValidators(FormComponent component) {
				component.setRequired(true);
			}
		});
		
		columns.add(new DateTimeColumn(Model.of("有效截止日期"), "validTo","VALID_TO",ColumnType.DateTime.DATE){
			private static final long serialVersionUID = 1L;

			@SuppressWarnings("unchecked")
			@Override
			protected void addValidators(FormComponent component) {
				component.setRequired(true);
			}
		});
		
		return columns;
	}	

	private void insert(AjaxRequestTarget target){
		Position pos = new Position();
		pos.setId(GUID.nextUUID());
		pos.setOrganId(organId);
		try {
			pos.setValidTo(new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse("2999-12-31").getTime()));
		} catch (ParseException e) {			
		}
		tableModel.addRow(pos);
		target.addComponent(getPage());
	}
	
	@SuppressWarnings("unchecked")
	private void deleteSelected(AjaxRequestTarget target){
		if (grid.getSelectedItems().size()>0){ 
			getMessageBox().question("确定要删除"+grid.getSelectedItems().size()+"条记录吗？",new MessageBox.DialogCallback(){
				private static final long serialVersionUID = 1L;

				public void onDialogClosed(AjaxRequestTarget target,
						ReturnType result) {
					if (result == ReturnType.YES){
						for (Iterator iterator = grid.getSelectedItems().iterator(); iterator.hasNext();) {
							IModel rowModel = (IModel) iterator.next();
							//删除前一定要先将所选行设为未选
							grid.selectItem(rowModel,false);
							Position t = (Position) (rowModel).getObject();
							tableModel.removeRow(t);
						}
						target.addComponent(getPage());
					}
				}
			});
		} else {
			getMessageBox().error("请选择要删除的记录!");
		}
	}
	
	private void postIt(AjaxRequestTarget target){
		for (Iterator<Position> iterator = tableModel.iterator(); iterator.hasNext();) {
			Position t = iterator.next();
			conn.execute(t, ExecMode.CREATE);
		}
		tableModel.clear();
		//清空已选行
		grid.resetSelectedItems();
		target.addComponent(getPage());
	}		
	 
}
